﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mysoft.MyCM.Web.Controllers.WebApi
{
	/// <summary>
	/// 基础Api控制器调用参数
	/// </summary>
	internal class BaseApiCalledParams
	{
		/// <summary>
		/// 请求WebApi的客户端App
		/// </summary>
		public string FromApp { get; set; }
		/// <summary>
		/// 请求WebApi的使用客户端的用户
		/// </summary>
		public string FromUser { get; set; }
		/// <summary>
		/// 请求WebApi的使用客户端的用户
		/// </summary>
		public string FromUserName { get; set; }
		/// <summary>
		/// 请求WebApi的使用客户端用户客户机IP
		/// </summary>
		public string FromIP { get; set; }
		/// <summary>
		/// 请求调用的WebApi动作
		/// </summary>
		public string CalledWebApiVerb { get; set; }
		/// <summary>
		/// 请求调用的WebApi地址
		/// </summary>
		public string CalledWebApiUrl { get; set; }

		/// <summary>
		/// 从请求头中解析调用参数
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public static BaseApiCalledParams GetParamsFromRequestHeader(System.Net.Http.HttpRequestMessage request)
		{
			var callParams = new BaseApiCalledParams();
			IEnumerable<string> fromApps;
			request.Headers.TryGetValues("from-app", out fromApps);
			if (fromApps != null && fromApps.Count() > 0) callParams.FromApp = fromApps.ToList()[0];

			IEnumerable<string> fromUsers;
			request.Headers.TryGetValues("from-user", out fromUsers);
			if (fromUsers != null && fromUsers.Count() > 0) callParams.FromUser = fromUsers.ToList()[0];

			IEnumerable<string> fromUserNames;
			request.Headers.TryGetValues("from-user-name", out fromUserNames);
			if (fromUserNames != null && fromUserNames.Count() > 0) callParams.FromUserName = M.Web.Util.UrlDecode(fromUserNames.ToList()[0]);

			IEnumerable<string> fromIPs;
			request.Headers.TryGetValues("from-ip", out fromIPs);
			if (fromIPs != null && fromIPs.Count() > 0) callParams.FromIP = fromIPs.ToList()[0];
			if (string.IsNullOrEmpty(callParams.FromIP)) callParams.FromIP = "unknown";

			callParams.CalledWebApiVerb = request.Method.ToString();
			callParams.CalledWebApiUrl = request.RequestUri.AbsoluteUri;

			return callParams;
		}
	}
}